﻿@model ShipmentListModel

@{
    var defaultGridPageSize = EngineContext.Current.Resolve<SDF.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
    var gridPageSizes = EngineContext.Current.Resolve<SDF.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;

    //page title
    ViewBag.Title = T("Admin.Orders.Shipments.List").Text;
    //active menu item (system name)
    Html.SetActiveMenuItemSystemName("Shipments");
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="content-header clearfix">
        <h1 class="pull-left">
            @T("Admin.Orders.Shipments.List")
        </h1>
        <div class="pull-right">
            <div class="btn-group">
                <button type="button" class="btn bg-purple">
                    <i class="fa fa-file-pdf-o"></i>
                    @T("Admin.Orders.Shipments.PrintPackagingSlips")
                </button>
                <button type="button" class="btn bg-purple dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">&nbsp;</span>
                </button>
                <ul class="dropdown-menu" role="menu">
                    <li><button type="submit" name="exportpackagingslips-all">
                            @T("Admin.Orders.Shipments.PrintPackagingSlips.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportpackagingslips-selected">
                            @T("Admin.Orders.Shipments.PrintPackagingSlips.Selected")
                        </button>
                    </li>
                </ul>
            </div>
            <button type="button" id="ship-selected" class="btn bg-aqua">
                <i class="fa fa-truck"></i>
                @T("Admin.Orders.Shipments.ShipSelected")
            </button>
            <button type="button" id="deliver-selected" class="btn bg-green">
                <i class="fa fa-check-square-o"></i>
                @T("Admin.Orders.Shipments.DeliverySelected")
            </button>
        </div>
    </div>
    <div class="content">
        <div class="form-horizontal">
            <div class="panel-group">
                <div class="panel panel-default panel-search">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.StartDate)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFEditorFor(model => model.StartDate)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.EndDate)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFEditorFor(model => model.EndDate)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.TrackingNumber)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFEditorFor(model => model.TrackingNumber)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.CountryId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownListFor(model => model.CountryId, Model.AvailableCountries)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.StateProvinceId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownListFor(model => model.StateProvinceId, Model.AvailableStates)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.City)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFEditorFor(model => model.City)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.WarehouseId)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFDropDownList("WarehouseId", Model.AvailableWarehouses)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.SDFLabelFor(model => model.LoadNotShipped)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.SDFEditorFor(model => model.LoadNotShipped)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-8 col-md-offset-4">
                                        <button type="button" id="search-shipments" class="btn btn-primary btn-search">
                                            <i class="fa fa-search"></i>
                                            @T("Admin.Common.Search")
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-body">
                        <div id="shipments-grid"></div>

                        <script>
                            $(document).ready(function () {
                                $("#shipments-grid").kendoGrid({
                                    dataSource: {
                                        type: "json",
                                        transport: {
                                            read: {
                                                url: "@Html.Raw(Url.Action("ShipmentListSelect", "Order"))",
                                                type: "POST",
                                                dataType: "json",
                                                data: additionalData
                                            }
                                        },
                                        schema: {
                                            data: "Data",
                                            total: "Total",
                                            errors: "Errors"
                                        },
                                        error: function(e) {
                                            display_kendoui_grid_error(e);
                                            // Cancel the changes
                                            this.cancelChanges();
                                        },
                                        pageSize: @(defaultGridPageSize),
                                        serverPaging: true,
                                        serverFiltering: true,
                                        serverSorting: true
                                    },
                                    pageable: {
                                        refresh: true,
                                        pageSizes: [@(gridPageSizes)]
                                    },
                                    //details grid
                                    detailInit: detailInit,
                                    scrollable: false,
                                    dataBound: onDataBound,
                                    columns: [{
                                        field: "Id",
                                        headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
                                        headerAttributes: { style: "text-align:center" },
                                        attributes: { style: "text-align:center" },
                                        template: "<input type='checkbox' value='#=Id#' class='checkboxGroups'/>",
                                        width: 50
                                    }, {
                                        field: "Id",
                                        title: "@T("Admin.Orders.Shipments.ID")",
                                        width: 50
                                    }, {
                                        field: "OrderId",
                                        title: "@T("Admin.Orders.Shipments.OrderID")",
                                        width: 100
                                    }, {
                                        field: "TrackingNumber",
                                        title: "@T("Admin.Orders.Shipments.TrackingNumber")",
                                        width: 100
                                    }, {
                                        field: "TotalWeight",
                                        title: "@T("Admin.Orders.Shipments.TotalWeight")",
                                        width: 100
                                    }, {
                                        field: "ShippedDate",
                                        title: "@T("Admin.Orders.Shipments.ShippedDate")",
                                        width: 200,
                                        type: "date",
                                        format: "{0:G}"
                                    }, {
                                        field: "DeliveryDate",
                                        title: "@T("Admin.Orders.Shipments.DeliveryDate")",
                                        width: 200,
                                        type: "date",
                                        format: "{0:G}"
                                    }, {
                                        field: "Id",
                                        title: "@T("Admin.Common.View")",
                                        width: 50,
                                        template: '<a href="@Url.Content("~/Admin/Order/ShipmentDetails/")#=Id#">@T("Admin.Common.View")</a>'
                                    }]
                                });
                            });

                            //details grid
                            function detailInit(e) {
                                $("<div/>").appendTo(e.detailCell).kendoGrid({
                                    dataSource: {
                                        type: "json",
                                        transport: {
                                            read: {
                                                url: "@Html.Raw(Url.Action("ShipmentsItemsByShipmentId", "Order"))?shipmentId="+e.data.Id,
                                                type: "POST",
                                                dataType: "json",
                                                data: addAntiForgeryToken
                                            }
                                        },
                                        schema: {
                                            data: "Data",
                                            total: "Total",
                                            errors: "Errors"
                                        },
                                        error: function(e) {
                                            display_kendoui_grid_error(e);
                                            // Cancel the changes
                                            this.cancelChanges();
                                        },
                                        serverPaging: true,
                                        serverFiltering: true,
                                        serverSorting: true
                                    },
                                    scrollable: false,
                                    sortable: true,
                                    pageable: {
                                        refresh: true,
                                        numeric: false,
                                        previousNext: false,
                                        info: false
                                    },
                                    columns: [
                                        {
                                            field: "ProductName",
                                            title: "@T("Admin.Orders.Shipments.Products.ProductName")",
                                            width: 400
                                        },{
                                            field: "ShippedFromWarehouse",
                                            title: "@T("Admin.Orders.Shipments.Products.Warehouse")",
                                            width: 150
                                        },{
                                            field: "QuantityInThisShipment",
                                            title: "@T("Admin.Orders.Shipments.Products.QtyShipped")",
                                            width: 150
                                        },{
                                            field: "ItemWeight",
                                            title: "@T("Admin.Orders.Shipments.Products.ItemWeight")",
                                            width: 150
                                        },{
                                            field: "ItemDimensions",
                                            title: "@T("Admin.Orders.Shipments.Products.ItemDimensions")",
                                            width: 150
                                        }
                                    ]
                                });
                            }
                        </script>
                    </div>
                </div>

                <script type="text/javascript">
                    var selectedIds = [];

                    $(document).ready(function() {
                        //load states when changing a country dropdownlist
                        $("#@Html.FieldIdFor(model => model.CountryId)").change(function() {
                            var selectedItem = $(this).val();
                            var ddlStates = $("#@Html.FieldIdFor(model => model.StateProvinceId)");
                            $.ajax({
                                cache: false,
                                type: "GET",
                                url: "@(Url.Action("GetStatesByCountryId", "Country"))",
                                data: { "countryId": selectedItem, "addAsterisk": "true" },
                                success: function(data) {
                                    ddlStates.html('');
                                    $.each(data, function(id, option) {
                                        ddlStates.append($('<option></option>').val(option.id).html(option.name));
                                    });
                                },
                                error: function(xhr, ajaxOptions, thrownError) {
                                    alert('Failed to retrieve states.');
                                }
                            });
                        });

                        $("".concat("#@Html.FieldIdFor(model => model.TrackingNumber),",
                            "#@Html.FieldIdFor(model => model.City)")).keydown(function(event) {
                                if (event.keyCode === 13) {
                                    $("#search-shipments").click();
                                    return false;
                                }
                            });

                        //search button
                        $('#search-shipments').click(function() {
                            //search
                            var grid = $('#shipments-grid').data('kendoGrid');
                            grid.dataSource.page(1); //new search. Set page size to 1
                            //grid.dataSource.read(); we already loaded the grid above using "page" function
                            //clear selected checkboxes
                            $('.checkboxGroups').attr('checked', false).change();
                            selectedIds = [];
                            return false;
                        });

                        //"ship selected" button
                        $('#ship-selected').click(function(e) {
                            e.preventDefault();

                            var postData = {
                                selectedIds: selectedIds
                            };
                            addAntiForgeryToken(postData);

                            $.ajax({
                                cache: false,
                                type: "POST",
                                url: "@(Url.Action("SetAsShippedSelected", "Order"))",
                                data: postData,
                                complete: function(data) {
                                    //reload grid
                                    var grid = $('#shipments-grid').data('kendoGrid');
                                    grid.dataSource.read();
                                },
                                error: function(xhr, ajaxOptions, thrownError) {
                                    alert(thrownError);
                                },
                                traditional: true
                            });
                            return false;
                        });

                        //"deliver selected" button
                        $('#deliver-selected').click(function(e) {
                            e.preventDefault();

                            var postData = {
                                selectedIds: selectedIds
                            };
                            addAntiForgeryToken(postData);

                            $.ajax({
                                cache: false,
                                type: "POST",
                                url: "@(Url.Action("SetAsDeliveredSelected", "Order"))",
                                data: postData,
                                complete: function(data) {
                                    //reload grid
                                    var grid = $('#shipments-grid').data('kendoGrid');
                                    grid.dataSource.read();
                                },
                                error: function(xhr, ajaxOptions, thrownError) {
                                    alert(thrownError);
                                },
                                traditional: true
                            });
                            return false;
                        });

                        $('#mastercheckbox').click(function() {
                            $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
                        });

                        //wire up checkboxes.
                        $('#shipments-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function(e) {
                            var $check = $(this);
                            if ($check.is(":checked") == true) {
                                var checked = jQuery.inArray($check.val(), selectedIds);
                                if (checked == -1) {
                                    //add id to selectedIds.
                                    selectedIds.push($check.val());
                                }
                            } else {
                                var checked = jQuery.inArray($check.val(), selectedIds);
                                if (checked > -1) {
                                    //remove id from selectedIds.
                                    selectedIds = $.grep(selectedIds, function(item, index) {
                                        return item != $check.val();
                                    });
                                }
                            }
                            updateMasterCheckbox();
                        });
                    });

                    function additionalData() {
                        var data = {
                            StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
                            EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
                            TrackingNumber: $('#@Html.FieldIdFor(model => model.TrackingNumber)').val(),
                            CountryId: $('#@Html.FieldIdFor(model => model.CountryId)').val(),
                            StateProvinceId: $('#@Html.FieldIdFor(model => model.StateProvinceId)').val(),
                            City: $('#@Html.FieldIdFor(model => model.City)').val(),
                            WarehouseId: $('#@Html.FieldIdFor(model => model.WarehouseId)').val(),
                            LoadNotShipped: $('#@Html.FieldIdFor(model => model.LoadNotShipped)').is(':checked')
                        };
                        addAntiForgeryToken(data);
                        return data;
                    }

                    function onDataBound(e) {
                        $('#shipments-grid input[type=checkbox][id!=mastercheckbox]').each(function() {
                            var currentId = $(this).val();
                            var checked = jQuery.inArray(currentId, selectedIds);
                            //set checked based on if current checkbox's value is in selectedIds.
                            $(this).attr('checked', checked > -1);
                        });

                        updateMasterCheckbox();
                    }

                    function updateMasterCheckbox() {
                        var numChkBoxes = $('#shipments-grid input[type=checkbox][id!=mastercheckbox]').length;
                        var numChkBoxesChecked = $('#shipments-grid input[type=checkbox][id!=mastercheckbox]:checked').length;
                        $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
                    }
                </script>
            </div>
        </div>
    </div>
}

@*export selected (Excel). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("PdfPackagingSlipSelected", "Order", FormMethod.Post, new { id = "pdf-packaging-slip-selected-form" }))
{
    @Html.AntiForgeryToken()
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}

<script type="text/javascript">
    $(document).ready(function () {
        $('#exportpackagingslips-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#pdf-packaging-slip-selected-form #selectedIds').val(ids);
            $('#pdf-packaging-slip-selected-form').submit();
            return false;
        });
    });
</script>